package robot;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.*;

import robot.PMF;


@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class BlipData {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;

@Persistent
private String name;

@NotPersistent
private static PersistenceManager pm;

public Long getId() {
	return id;
}

public void setName(String name) {
	this.name = name;
}

public String getName() {
	return name;
}

public BlipData(String name) {
	this.setName(name);
}

/**
* Returns the PersistenceManager for the Cocktail Class, creates one if not
* existent or closed
*
* @return PersistenceManager
*/
private static PersistenceManager getPersistenceManager() {
	if (pm == null) {
		pm = PMF.get().getPersistenceManager();
	} else if (pm.isClosed()) {
		pm = PMF.get().getPersistenceManager();
	}
	return pm;
}

/**
* Finds the Cocktail in the database by the given id
*
* @param id
* integer with the id of the Cocktail
* @return Cocktail object found in the database
*/
public static BlipData find(int id) {
	BlipData blipdata = BlipData.getPersistenceManager().getObjectById(
	BlipData.class, id);
	return blipdata;
}

/**
* Makes the Cocktail object persistent
*
* @return boolean true if successful, false if not
*/
public boolean persist() {
	boolean wasSuccessful;
	try {
		getPersistenceManager().makePersistent(this);
		wasSuccessful = true;
	} catch (Exception e) {
		wasSuccessful = false;
	} finally {
		getPersistenceManager().close();
	}
	return wasSuccessful;
}

/**
* Deletes the Cocktail object from the persistent storage
*
* @return
*/
public boolean delete() {
	boolean wasSuccessful;
	try {
		getPersistenceManager().deletePersistent(this);
		wasSuccessful = true;
	} catch (Exception e) {
		wasSuccessful = false;
	} finally {
		getPersistenceManager().close();
	}
	return wasSuccessful;
}

/**
* Returns all Cocktails as a List from the persistent storage
*
* @return
*/
@SuppressWarnings("unchecked")
public static List findAll() {
	String sqlFetchAll = "select from " + BlipData.class.getName();
	Query query = BlipData.getPersistenceManager().newQuery(sqlFetchAll);
	List cocktails = (List) query.execute();
	return cocktails;
}

}